<template>
  <div class="tag-container">
    <el-form :model="addTagForm" :rules="addRules" ref="addRef" label-width="100px" class="addForm">
      <el-form-item label="所属学科" v-if="!id" prop="subjectID">
        <el-select v-model="addTagForm.subjectID">
          <el-option v-for="(item, i) in subjectList" :label="item.label" :value="item.value" :key="i"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签名称" prop="tagName" class="tagName">
        <el-input v-model="addTagForm.tagName" placeholder="请输入标签名称"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button type="primary" @click="addTag">确 定</el-button>
    </span>
  </div>
</template>

<script>
import { update, add } from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'
export default {
  data () {
    return {
      // 学科列表
      subjectList: [],
      // 添加标签的数据
      addTagForm: {
        subjectID: null,
        tagName: null
      },
      addRules: {
        tagName: [
          { required: true, message: '标签名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    // 弹框内容控件
    text: {
      required: true,
      type: String
    },
    // 下拉列表的显示控件
    id: {
      required: true,
      default: () => null
    },
    editData: {
      type: [Object, Array],
      default: () => { }
    }
  },
  created () {
    // 如果是当前的页面,进入页面,需要获取学科列表,渲染到下拉列表中
    if (!this.id) {
      this.getSubjects()
    }
    this.addTagForm.subjectID = this.editData.subjectID || this.id
    // 判断是否是修改
    if (this.text === '修改') {
      this.addTagForm.tagName = this.editData.tagName
    }
  },
  methods: {
    // 获取学科的简单列表
    async getSubjects () {
      try {
        const { data } = await simple()
        this.subjectList = data
      } catch (err) {
        this.$message.error('获取学科失败,请重试')
      }
    },
    // 新增标签或者修改标签
    addTag () {
      this.$refs.addRef.validate(async valid => {
        if (valid) {
          try {
            // 发送新增请求
            if (this.text === '新增') {
              const res = await add(this.addTagForm)
            } else {
              // 发送修改请求
              const res = await update({
                id: this.editData.id,
                subjectID: this.addTagForm.subjectID,
                tagName: this.addTagForm.tagName
              })
            }
            this.$message.success(this.text + '标签成功')
          } catch (err) {
            this.$message.error('操作失败,请重试')
          }
          this.$emit('close')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.tag-container {
  .dialog-footer {
    display: block;
    text-align: center;
  }
  .addForm {
    ::v-deep .el-select {
      width: 100%;
    }
    .tagName {
      margin-top: 15px;
    }
  }
}
</style>
